<?php

use Biz\model\Album\AlbumListModel;
use Biz\model\Album\AlbumWikiListModel;
use Biz\service\Album\AlbumListService;
use Doraemon\tools\Log;

class SaveAlbumWikiAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_NOTHING;

    /**
     * @throws \Exception
     */
    public function main()
    {
        $currUid = $this->uid;

        $albumId = $this->getRequest()->getPost('album_id', '');
        $wikiId = $this->getRequest()->getPost('wiki_id', '');
        Log::info('把商品添加至清单/SaveAlbumWiki', ['albumId' => $albumId, 'wikiId' => $wikiId]);
        try {
            if (!$currUid) {
                throw new \Exception("请登录重试！");
            }

            $isCanBuiltAlbum = AlbumListService::checkIsCanBuiltAlbum($currUid);
            if (!$isCanBuiltAlbum) {
                throw new Exception("保存失败，你还没有创建权限哦~");
            }
            //获取清单信息
            $albumInfo = AlbumListModel::getAlbumById($albumId);
            if (empty($albumInfo)) {
                throw new \Exception('好物清单不存在');
            }
            //验证当前清单商品数量
            if ($albumInfo['wiki_count'] >= AlbumListModel::ALBUM_WIKI_LIMIT) {
                throw new Exception('商品数量超过限制');
            }
            //验证清单归属
            if ($currUid != $albumInfo['uid']) {
                throw new Exception('非法操作，只能编辑您自己的清单');
            }
            //验证是否重复
            $wikiIdsOld = AlbumWikiListModel::selectByWhere(['album_id'=>$albumId,'status'=>AlbumWikiListModel::STATUS_NORMAL],'wiki_id');
            if(in_array($wikiId,$wikiIdsOld)){
                throw new Exception('商品已存在');
            }
            AlbumListService::SaveAlbumWiki($currUid,$albumId, $wikiId,($albumInfo['wiki_count']+1) , $wikiIdsOld , $albumInfo['quality'] ?? 0);
            $this->setSuccess(['album_id'=>$albumId,'title'=>$albumInfo['title']], self::API_CODE_SUCCES);

        } catch (Exception $exception) {

            Log::error('把商品添加至清单', [
                'currUid' => $currUid,
                'albumId' => $albumId,
                'wiki_id' => $wikiId,
            ]);
            throw new Exception($exception->getMessage(), $exception->getCode());
        }

    }
}